<!--异常记录-->
<template>
  <div class="white-list">
    <div class="title">异常记录</div>
    <el-form :inline="true" class="search-form">
      <el-form-item class="date">
        <el-date-picker
          v-model="dateValue"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="date-picker"
          clearable
          :style="{ width: '330px' }"
          :default-time="['00:00:00', '23:59:59']"
          @blur="isRestart = true">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        异常类型
        <el-select
          v-model="type"
          placeholder="请选择"
          clearable>
          <el-option
            v-for="item in logTypeData"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        状态
        <el-select
          v-model="status"
          placeholder="请选择"
          clearable>
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="search-btn">
        <el-button type="primary" :disabled="!multipleSelection.length" class="btn-export" size="14" @click="handleExport">导出</el-button>
        <el-button type="primary" class="btn-query" size="14" @click="queryList('search')">查询</el-button>
      </div>
    </el-form>
    <div class="num-title">总数量：{{ infoData.totalAmount }}，未处理数量：{{ infoData.pendingAmount }}</div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="时间">
        <template slot-scope="scope">
          {{ scope.row.createTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="异常类型">
        <template slot-scope="scope">
          {{ scope.row.type === 0 ? '三元组' : '白名单' }}
        </template>
      </el-table-column>
      <el-table-column label="设备标识">
        <template slot-scope="scope">
          <div v-if="scope.row.type === 1">
            {{ scope.row.deviceIdentification || '-' }}
          </div>
          <div v-else>
            <div>{{ scope.row.deviceName || '-' }}</div>
            <div>{{ scope.row.deviceSecret || '-' }}</div>
            <div>{{ scope.row.productKey || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">未处理</span>
          <span v-else>已处理</span>
        </template>
      </el-table-column>
      <el-table-column label="异常原因">
        <template slot-scope="scope">
          {{ scope.row.exceptionReason || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="处理意见">
        <template slot-scope="scope">
          {{ scope.row.handlingOpinion || "-" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button v-if="scope.row.type === 0 && scope.row.status === 0" type="text" size="operate" @click="jumpDetails(scope.row)">查看</el-button>
          <el-button
            v-if="!scope.row.status"
            type="text"
            size="operate"
            @click="handleReason(scope.row.id)">处理</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog
      title="处理意见"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        :model="addFormData"
        :rules="rules"
        width="596px"
        label-width="80px"
        label-position="right">
        <el-form-item label="处理意见" prop="handlingOpinion">
          <el-input
            v-model="addFormData.handlingOpinion"
            placeholder="请输入处理意见，1~100字符"
            type="textarea"
            maxlength="100"
            show-word-limit
            :rows="6"
            clearable>
          </el-input>
          <span class="tips">点击确认后，该异常记录状态已处理</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="异常三元组查询结果" :visible.sync="dialogViewVisible" custom-class="view-dialog">
      <div>
        <div>DeviceName：{{ gridData.length && gridData[0].deviceNameError || '-' }}</div>
        <div>DeviceSecret：{{ gridData.length && gridData[0].deviceSecretError || '-' }}</div>
        <div>ProductKey：{{ gridData.length && gridData[0].productKeyError || '-' }}</div>
      </div>
      <div class="view-title">标记的为与当前设备不匹配项。若列表无结果，则表示未生成过相关联三元组</div>
      <el-table :data="gridData">
        <el-table-column label="订单号">
          <template slot-scope="scope">
            {{ scope.row.orderNo || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="产品PID">
          <template slot-scope="scope">
            {{ scope.row.productId || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="DeviceName">
          <template slot-scope="scope">
            {{ scope.row.deviceNameCorrect || "-" }}
            <span :class="{'text-danger': !scope.row.deviceNameIsCorrect}">
              {{ scope.row.deviceNameCorrect || '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="DeviceSecret">
          <template slot-scope="scope">
            <span :class="{'text-danger': !scope.row.deviceSecretIsCorrect}">
              {{ scope.row.deviceSecretCorrect || '-' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="ProductKey">
          <template slot-scope="scope">
            {{ scope.row.productKeyCorrect || "-" }}
            <span :class="{'text-danger': !scope.row.productKeyIsCorrect}">
              {{ scope.row.productKeyCorrect || '-' }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button size="14" @click="dialogViewVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getList, update, statistics, exports, exceptionDetail } from '@/api/device-identity-auth/abnormal-records'
export default {
  name: 'abnormalRecords',
  data() {
    return {
      tableData: [], // 列表数据
      infoData: {}, // 信息数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      addFormData: {
        handlingOpinion: '' // 异常原因
      },
      type: '', // 异常类型
      status: '', // 状态
      multipleSelection: [], // 多选数据
      dateValue: [], // 日期范围
      logTypeData: [
        { label: '全部', value: '' },
        { label: '白名单异常', value: 1 },
        { label: '三元组异常', value: 0 }
      ],
      statusList: [
        { label: '全部', value: '' },
        { label: '已处理', value: 1 },
        { label: '未处理', value: 0 }
      ],
      dialogViewVisible: false, // 查看弹窗
      gridData: [], // 未处理三元组查询结果数据
      rules: {
        handlingOpinion: [
          { required: true, message: '请输入处理意见', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      id: ''
    }
  },
  created() {
    this.queryList()
    this.getStatistics()
    this.getLogType()
  },
  methods: {
    /**
     * 查询列表
     */
    queryList(condition) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        size: this.pageSize,
        current: this.currentPage,
        type: this.type,
        status: this.status,
        startTime: this.dateValue && this.dateValue.length ? this.formatDate(this.dateValue[0]) : '',
        endTime: this.dateValue && this.dateValue.length ? this.formatDate(this.dateValue[1]) : ''
      }
      getList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 未处理三元组列表
    viewList(id) {
      this.loading = true
      const params = {
        id
      }
      exceptionDetail(params).then(res => {
        this.gridData = [res.data.data]
        console.log('gridData=====', this.gridData)
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 格式化日期的函数
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /**
     * 数量
     */
    getStatistics() {
      statistics().then(res => {
        this.infoData = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 查看
    jumpDetails(row) {
      this.dialogViewVisible = true
      this.viewList(row.id)
    },
    // 展示异常原因弹窗
    handleReason(id) {
      this.id = id
      this.dialogVisible = true
    },
    // 关闭新增订单弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    // 全选/多选
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    // 导出
    handleExport() {
      const params = {
        idList: this.multipleSelection
      }
      exports(params).then(res => {
        this.exportBlobFile(res)
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    /**
     * 新增订单
     */
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData,
            id: this.id
          }
          update(params).then(res => {
            this.dialogVisible = false
            this.id = ''
            this.$refs['form'].resetFields()
            this.$message.success('处理意见填写成功')
            this.queryList()
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    }
  }
}
</script>
<style lang="scss" scoped>
.white-list {
  .title {
    font-weight: 400;
    color: #252525;
    font-size: 18px;
  }

  .search-form {
    display: flex;
    align-items: center;
    margin-top: 20px;
    margin-bottom: 18px;

    .search-btn {
      margin-left: auto;

      .btn-export {
        margin-right: 10px;
      }
    }
  }

  .num-title {
    width: max-content;
    background: rgba(39, 95, 232, 0.1);
    padding: 10px;
    margin-bottom: 20px;
    color: #252525;
    margin-right: 20px;
    font-size: 18px;
  }

  .status-click {
    cursor: pointer;
    color: #275fe8;
  }

  .tips {
    font-size: 14px;
    font-weight: 400;
    color: #AEB0B9;
  }

  .view-title {
    margin: 15px 0;
  }

  .text-danger {
    color: #F56C6C;
  }
}
.el-form-item {
  margin-bottom: 0;
}
::v-deep .el-date-editor .el-range-separator {
  padding: 0 !important;
}

::v-deep .view-dialog .el-dialog__footer {
  text-align: center;
}
</style>
